#include "MobileScreen.h"
#include <shellapi.h>
#include <Regext.h>
#include <QtCore/QFile>
#include <QtGui/QDesktopWidget>
#include <QtGui/QImageWriter>
#include <QtGui/QImageReader>
#include <QtGui/QMessageBox>
#include <QtCore/QRect>
#include <QtGui/QApplication>
#include "Utility.h"
#include <QtGui/QProgressDialog>

#define REG_KEY_ROOT HKEY_CURRENT_USER
#define REG_KEY_TODAY TEXT("Software\\Microsoft\\Today")

MobileScreen::MobileScreen(QObject *parent)
: QObject(parent)
{

}

MobileScreen::~MobileScreen()
{

}

bool MobileScreen::setWallPaper(const QString& imgFile){
	QFile::remove("\\Windows\\tdywater.gif");
	QFile::remove("\\Windows\\tdywater.jpg");
	QFile::remove("\\Windows\\stwater.gif");
	QFile::remove("\\Windows\\stwater.jpg");

	if (!generateWallPaperFile(imgFile)){
		QMessageBox::warning(0,"Set WallPaper","Write wallpaper file failed!");
		return false;
	}

	RegistrySetDWORD( REG_KEY_ROOT, REG_KEY_TODAY, TEXT("UseStartImage"), 1 );
	RegistrySetString( REG_KEY_ROOT, REG_KEY_TODAY, TEXT("Wall"), TEXT("InterGrafx") );

	return true;
}

void MobileScreen::update(){
	PostMessage( HWND_BROADCAST, WM_WININICHANGE, 0xF2, 0 );
}

bool MobileScreen::generateWallPaperFile(const QString& srcImgFile){
	static QProgressDialog progress("Set WallPaper...", "Cancel", 0, 4);
	progress.setWindowModality(Qt::WindowModal);
	progress.setValue(0);

	QImageReader imgReader(srcImgFile);
	QSize imgSize(imgReader.size());
	if (imgSize.isValid()){
		QSize scrSize=QApplication::desktop()->screenGeometry().size();
		if (scrSize.width()<imgSize.width() || scrSize.height()<imgSize.height() ){
			imgSize.scale(scrSize,Qt::KeepAspectRatioByExpanding);
			imgReader.setScaledSize(imgSize);
			int quality=Utility::areaOfSize(imgSize)*75/Utility::areaOfSize(imgReader.size());
			imgReader.setQuality(quality+1);
		}
	}
	progress.setValue(1);
	if (progress.wasCanceled())
		return true;

	QImage img=imgReader.read();
	progress.setValue(2);
	if (progress.wasCanceled())
		return true;

	if (!img.isNull()){
		QImageWriter imgWriter;
		imgWriter.setFormat("JPG");
		imgWriter.setFileName("\\Windows\\stwater.jpg");
		if (!imgWriter.write(img))
			return false;
		progress.setValue(3);
		if (progress.wasCanceled())
			return true;

		imgWriter.setFileName("\\Windows\\tdywater.jpg");
		bool ret=imgWriter.write(img);
		progress.setValue(4);	
		return ret;
	}
	return false;
}
